package com.ljm.boot.nettywebsocket.netty.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 服务端
 */
public class NettyServer {

    public static void main(String[] args) {
        startServer("127.0.0.1", 7002);
    }

    /**
     * 启动客户端
     */
    public static void startServer(String hostName, int port) {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            NioEventLoopGroup mainLoopGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workLoopGroup = new NioEventLoopGroup();
            bootstrap.group(mainLoopGroup,workLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new StringDecoder());//解码器
                            p.addLast(new StringEncoder());//编码器
                            p.addLast(new ServerStub());//业务处理器提供方Stub
                        }
                    });
            bootstrap.bind(hostName, port).await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}